package foundation.tree.binaryTree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author hang an
 * @since 2025/7/13
 */
public class 完全二叉树 {
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) return true;
        boolean leaf = false;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode curNode = queue.poll();
                if (curNode.left == null && curNode.right != null || leaf && (curNode.left != null || curNode.right != null)) {
                    return false;
                }
                if (curNode.left != null) queue.add(curNode.left);
                if (curNode.right != null) queue.add(curNode.right);
                if (curNode.left == null || curNode.right == null) {
                    leaf = true;
                }
            }
        }
        return true;
    }


}
